package com.google.android.apps.skipbot;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;

import android.content.Context;
import android.util.Log;

public class Utilities {
  private static final String TAG = "Utilites";

  public static long map(long value, long inMin, long inMax, long outMin, long outMax) {
    if (value > inMax) {
      return outMax;
    }

    if (value < inMin) {
      return outMin;
    }

    return (value - inMin) * (outMax - outMin) / (inMax - inMin) + outMin;
  }

  public static boolean saveObject(Context context, String fileName, Object serializable) {
    BufferedOutputStream fos = null;
    try {
      try {

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(bos);
        out.writeObject(serializable);
        out.close();

        // Get the bytes of the serialized object
        fos = new BufferedOutputStream(context.openFileOutput(fileName, Context.MODE_PRIVATE));
        byte[] buf = bos.toByteArray();

        fos.write(buf);
      } finally {
        if (fos != null) {
          fos.close();
        }
      }
    } catch (IOException e) {
      Log.e(TAG, "Error writing config to local storage", e);
      return false;
    }
    return true;
  }

  public static Object loadObject(Context context, String fileName) {
    ObjectInputStream ois = null;
    try {
      try {
        BufferedInputStream bis = new BufferedInputStream(context.openFileInput(fileName));
        ois = new ObjectInputStream(bis);
        return ois.readObject();
      } catch (FileNotFoundException e) {
        Log.e(TAG, "Failed to load " + fileName, e);
      } catch (StreamCorruptedException e) {
        Log.e(TAG, "Failed to load " + fileName, e);
      } catch (IOException e) {
        Log.e(TAG, "Failed to load " + fileName, e);
      } catch (ClassNotFoundException e) {
        Log.e(TAG, "Failed to load " + fileName, e);
      }
    } finally {
      if (ois != null) {
        try {
          ois.close();
        } catch (IOException e) {
          Log.e(TAG, "Failed to load " + fileName, e);
        }
      }
    }
    return null;
  }
}
